$(function () {
    //获取点击按钮
    let $btn=$('#login-btn')
    $btn.click(function (e){
     //校验用户名
    let Username=$('input[name="name"]').val()
    if (Username===''){
        message.showError('用户名不能为空')
        return
    };
    if (!(/^\w{5,20}$/).test(Username)){
             message.showError('用户名格式不正确,请重新输入')
             return;
        };
    //检测密码
    let Password=$('input[name="password"]').val()
    if (Password===''){
        message.showError('密码不能为空')
        return;
    }
    //获取用户是否勾选'记住我'，勾选为true，否则为false
    let bRemember = $('input[name="radio"]').is(':checked');
    message.showInfo(bRemember)
    $.ajax(
        {
            url:'/user/login/',
            data: {
                username: Username,
                password: Password,
                remember: bRemember
            },
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if(res.errno === '0'){
                    message.showSuccess('恭喜， 登录成功！');
                    setTimeout(function () {
                        //注册成功之后重定向到打开登录页面之前的页面
                        if(!document.referrer || document.referrer.includes('/user/login/') || document.referrer.includes('/user/register/')){
                            window.location.href = '/'
                        }else {
                            window.location.href = document.referrer
                        }
                    }, 1000)
                }else{
                    message.showError(res.errmsg)
                }
            },
            error: function (xhr, msg) {
                message.showError('服务器超时，请重试')

            }


        }
    )
    })
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    });

});